<script lang="ts" setup>
import { ref, watch, computed, reactive, onMounted } from "vue";
import { formatTimestamp, formatBigNumber, scientificToDecimal } from "@/comm/format";
import { usePerson } from "@/stores/person";
import line from "@/assets/line.png";
import JEmpty from "@/components/j-empty/index.vue";
import NavBtn from "./NavBtn.vue";
import YHR from "./YHR.vue";
import Copy from "@/components/copy/index.vue";
import YTab from "./YTab.vue";
import { YTab as YTabscript } from "./scripts/YTab";
import JRecord from "@/components/j-record/index.vue";
import JNumber from "@/components/j-number/index.vue";
import { useTokens } from "@/stores/tokens";
import { useRouter } from "vue-router";
import { getTodayYesterdayBlocks, getTodayYesterdayPrice } from "@/comm/web3";
import i18n from "@/locals";
const router = useRouter();
const tokens = useTokens();
const capital = usePerson();
// const todayMap = ref<any>({});
// const yesterdayMap = ref<any>({});
const idx = ref(0);
//分页索引
const index = ref(1);
const index2 = ref(1);
const pageSize = 10;
const todayMap = ref<any>({});
const yesterdayMap = ref<any>({});
const pages = computed(() => Math.ceil(capital.positions.length / pageSize));
const listArr = computed({
    set: () => { },
    get: () => {
        let listArr = capital.positions.slice((index2.value - 1) * pageSize, index2.value * pageSize);
        return listArr;
    }
});

let todayNumber = 0;
let yesterdayNumber = 0;

onMounted(async () => {
    await capital.loadCapitals();
    updatePrice();
});

const prevListArr = computed({
    set: () => { },
    get: () => {
        let listArr = capital.prevPositions.slice((index2.value - 1) * pageSize, index2.value * pageSize);
        return listArr;
    }
});

watch(
    () => capital.positions,
    () => {
        index.value = 1;
        index2.value = 1;
    }
);

watch(
    () => listArr.value,
    newVal => {
        console.log("change list arr", listArr);
        updatePrice();
    }
);

let loading = false;
const updatePrice = async () => {
    if (listArr.value.length == 0) return;
    if (loading) return;
    loading = true;

    console.warn("listArr.value", listArr.value);
    let list = listArr.value.map(element => element.contractAddress);
    let res: any;
    res = await getTodayYesterdayPrice(false, list, Date.now() - 10 * 60 * 1000, 0, 0);
    console.warn("res---v3----", res);

    if (res["0x"]) {
        setPriceList(res);
    }
    let notGets = list.filter(i => {
        // if(i!="0x")
        if (res[i] && Object.keys(res[i]).length) {
            if (res[i].t == 0) {
                return true;
            }
            return false;
        }
        return true;
    });
    console.log("notGets", notGets);
    if (notGets.length) {
        // if (todayNumber + yesterdayNumber == 0) {
        //     let res: any = await getTodayYesterdayBlocks(Date.now() - 5 * 24 * 60 * 60 * 1000);
        //     todayNumber = res.today;
        //     yesterdayNumber = res.yesterday;
        // }
        res = await getTodayYesterdayPrice(true, notGets, Date.now() - 10 * 60 * 1000, todayNumber, yesterdayNumber);
        console.warn("res---v2----", res);

        if (res["0x"]) {
            setPriceList(res);
        }
    }
    loading = false;
    console.log(todayMap, yesterdayMap);
};

const setPriceList = (res: any) => {
    listArr.value.forEach(item => {
        let i = item.contractAddress;
        if (res[i]) {
            todayMap.value[i] = res[i]?.t || 0;
            yesterdayMap.value[i] = res[i]?.y || 0;
        }
    });
};

const onPage = async () => { };

const nvadown = function (val: number) {
    idx.value = val;
    index.value = 1;
    index2.value = 1;
};

watch(
    () => YTabscript.page.value,
    (newVal, oldVal) => {
        console.log("newVal", newVal);
        idx.value = newVal;
    }
);

const getPrice = (item: any) => {
    // return item.usd / (item.balance || 1);
    return todayMap.value[item.contractAddress] || 0;
};

const actionName = (item: any) => {
    if (item.method == "transfer") {
        if (item.inAmount > 0) {
            // return "充值"
            return i18n.global.t("message.YTabCol_.type.a");
        } else {
            // return "提现"
            return i18n.global.t("message.YTabCol_.type.b");
        }
    } else {
        // return "交易";
        return i18n.global.t("message.YTabCol_.type.c");
    }
};

const getColor = (item: any) => {
    if (item.method == "transfer") {
        if (item.inAmount > 0) {
            return "win-color";
        } else {
            return "lose-color";
        }
    } else {
        return "win-color";
    }
};
const onDetail = (coin: any) => {
    // router.push({ name: 'token', params: { id: coin.contractAddress } });
    window.open("/token/" + coin.contractAddress);
};

const getChangeUsd = (item: any) => {
    let res: any = prevListArr.value.find(i => i.symbol == item.symbol);
    if (res) {
        // return item.balance * todayMap.value[item.contractAddress] - res.balance * yesterdayMap.value[item.contractAddress];
        // return item.usd - res.usd;
        let nums = (item.balance - res.balance) * todayMap.value[item.contractAddress];
        return scientificToDecimal(nums)
    }
    // let res:any = prevListArr.value.find(i=>i.symbol==item.symbol);
    // if(res){
    //     return item.usd - res.usd;
    // }
    return scientificToDecimal(item.usd)
};

const getChangePrice = (item: any) => {
    let tp = todayMap.value[item.contractAddress];
    let yp = yesterdayMap.value[item.contractAddress];
    console.log(`${tp}-${yp}`, tp - yp);
    return tp - yp;
    // let newPrice = getPrice(item);
    // console.log("newPrice", newPrice)
    // let res:any = prevListArr.value.find(i=>i.symbol==item.symbol);
    // if(res){
    //     let oldPrice = getPrice(res);
    //     return newPrice - oldPrice;
    // }
    // return 0;
};
</script>

<template>
    <div class="ytabCol">
        <div v-show="idx == 0" class="c-title-5">
            <JRecord page="person"></JRecord>
        </div>
        <div v-show="idx == 1" class="c-title-4">
            <div class="tab-h c-title-4 c-bold">{{ idx == 0 ? $t("message.YTabCol_.a") : $t("message.YTabCol_.b") }}</div>
            <YHR></YHR>
            <VContainer style="position: relative">
                <JLoding v-if="capital.positionLoading"></JLoding>
                <VRow class="row-first">
                    <VCol class="col_title col_1 col-first">{{ $t("message.YTabCol_.tableB.a") }}</VCol>
                    <VCol class="col_title col_2">{{ $t("message.YTabCol_.tableB.c") }}</VCol>
                    <VCol class="col_title col_3 center">
                        {{ $t("message.YTabCol_.tableB.d") }}&nbsp;&nbsp;
                        {{ $t("message.YTabCol_.tableB.dd") }}
                    </VCol>
                    <VCol class="col_title col_4">{{ $t("message.YTabCol_.tableB.b") }}</VCol>
                </VRow>
                <div class="j-auto">
                    <VRow v-for="(item, i) in listArr">
                        <VCol class="col_1 sps-col col-first">
                            <img :src="tokens.getImg(item.symbol)" class="mr-2 coin-t" />
                            <span>{{ item.symbol }}</span>&nbsp;
                        </VCol>
                        <VCol class="col_2 sps-col">
                            <JNumber :num="todayMap[item.contractAddress]" prefix="$" price></JNumber>
                            <!-- <JNumber :num="getPrice(item)" prefix="$"></JNumber> -->
                            <!-- <JNumber :num="getChangePrice(item)" :is-color="true" prefix="$" origin price></JNumber> -->
                        </VCol>
                        <VCol class="col_3 c-title-4 money align-center">
                            <div class="left-m long-txt">{{ formatBigNumber(item.balance) }}</div>
                            <div class="right-m long-txt coin-link" @click="onDetail(item)">{{ item.symbol }}</div>
                        </VCol>
                        <VCol class="col_4 sps-col">
                            <div class="c-left">
                                <JNumber :num="item.balance * todayMap[item.contractAddress]" prefix="$" price></JNumber>
                            </div>
                            <div class="c-right">
                                <JNumber :num="+getChangeUsd(item)" :is-color="true" prefix="$" origin price> </JNumber>
                            </div>
                        </VCol>
                    </VRow>
                    <JEmpty v-show="(listArr && listArr.length == 0) || !listArr"></JEmpty>
                </div>
            </VContainer>
            <v-pagination class="my-4" v-if="capital.positions.length > 0" size="small" :length="pages" :total-visible="3"
                @update:modelValue="onPage" v-model="index2"></v-pagination>
            <!-- <div>
                                                                                                                                                                        <JEmpty v-else></JEmpty>
                                                                                                                                                                    </div> -->
            <!-- <v-pagination :length="4"></v-pagination> -->
        </div>
    </div>
</template>

<style lang="less" scoped>
.ytabCol {
    background-color: #1d2125;
    border-radius: 4px;

    .col_title {
        text-align: left;
        // font-size: 12px;
        // font-family: PingFangSC-Regular, PingFang SC;
        // font-weight: 400;
        color: #b1b6c6;
        line-height: 17px;

        .icon {
            font-size: 15px;
        }
    }

    .image {
        width: 20px;
        height: 20px;
    }

    .col_1 {
        width: 51px;
        font-family:
            PingFangSC-Regular,
            PingFang SC;
        line-height: 20px;
        padding-left: 20px;
    }

    .col_3 {
        // font-size: 14px;
        font-family:
            PingFangSC-Regular,
            PingFang SC;
        line-height: 20px;
    }

    .col_4 {
        text-align: center;
        justify-content: center;
        padding-right: 20px;
        // background-color: red;
        display: flex;
        align-items: center;

        .c-left {
            flex: 1 0 0;
            width: 0;
            text-align: right;
        }

        .c-right {
            flex: 1 0 0;
            width: 0;
            margin-left: 4px;
            text-align: left;
        }
    }

    .v-row {
        border-bottom: 1px solid #2d3338;
        margin: 0 !important;
        height: 50px;
    }

    :deep(.i-navs) {
        margin-top: 0;
    }
}

.bodyList {
    overflow-x: hidden;
    overflow-y: scroll;
    height: 480px;
}

.col-first {
    padding-inline-start: 50px;
}

.j-auto,
.j-none {
    height: 500px;
    overflow-x: hidden;
    overflow-y: scroll;
}

.tab-h {
    padding: 20px;
}

.row-first {
    border-bottom: 1px solid #2d3338;
    background: #1d2125;
    position: relative;
    z-index: 1;
    margin: 0 !important;
}

.v-container {
    padding: 0 !important;
    max-width: 100% !important;
}

.money {
    display: flex;

    .left-m {
        flex: 1;
        width: 0;
        text-align: right;
    }

    .right-m {
        flex: 1;
        width: 0;
        text-align: left;
        margin-left: 12px;
    }
}

.center {
    text-align: center !important;
    flex-grow: 2 !important;
}

.money {
    flex-grow: 2 !important;
}

.coin-t {
    width: 20px;
    height: 20px;
    background: #b3b3b3;
    border-radius: 50%;
    overflow: hidden;
    object-fit: contain;
}

.sps-col {
    display: flex;
    align-items: center;
    gap: 12px;
}
</style>